package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DeviceInfoDTO;
import edu.ynu.se.xiecheng.achitectureclass.dto.GreenHouseDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class GreenhouseService extends LogicService<GreenhouseDao, Greenhouse,Long> {
    public GreenhouseService(@Autowired  GreenhouseDao dao) {super(dao);}

    //添加一个默认的大棚信息
    @Transactional
    public void addDefaultGreenhouse(){
        if (dao.count() > 0){return;}
        Greenhouse gh = new Greenhouse();
        gh.setArea(100.0);
        gh.setAddress("云南省昆明市呈贡区云南大学呈贡校区");
        gh.setName("虚拟大棚");
        dao.save(gh);
    }

    //获取大棚的信息
    @Transactional
    public GreenHouseDTO getGreenhouseInfo(Long id){
        Greenhouse greenhouse = new Greenhouse();
        if(dao.findById(id).isPresent()){
            greenhouse = dao.findById(id).get();
        }
        GreenHouseDTO greenHouseDTO = new GreenHouseDTO();
        greenHouseDTO.setName(greenhouse.getName());
        greenHouseDTO.setArea(greenhouse.getArea());
        greenHouseDTO.setAddress(greenhouse.getAddress());
        return greenHouseDTO;
    }
    //获取设备信息
    @Transactional
    public List<DeviceInfoDTO> getGreenhouseDevicesInfo(Long id){
        List<DeviceInfoDTO> deviceInfoDTOS = new ArrayList<>();
        List<Device> devices = getGreenhouseDevices(id);
        for(Device device:devices){
            DeviceInfoDTO deviceInfoDTO = new DeviceInfoDTO();
            deviceInfoDTO.setId(device.getId());
            deviceInfoDTO.setName(device.getName());
            deviceInfoDTO.setType(device.getType());
            deviceInfoDTOS.add(deviceInfoDTO);
        }
        return deviceInfoDTOS;
    }

    //获取大棚绑定的所有设备
    @Transactional
    public List<Device> getGreenhouseDevices(Long id){
        Greenhouse gh = new Greenhouse();
        List<DeviceInfoDTO> deviceInfoDTOS = new ArrayList<>();
        if(dao.findById(id).isPresent()){
            gh = dao.findById(id).get();
        }
        return gh.getDevices();
    }

}
